package cn.example.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 通用工具类
 * Created by Administrator on 2016/12/6.
 */
public class CommUtil {

    private static final Logger log = LoggerFactory.getLogger(CommUtil.class);

    /**
     * 生成16位的时间戳字符串
     */
    public static String getTimeStr() {
        String formatDate = new SimpleDateFormat("yyMMddHHmmss").format(new Date());  	/* Warning: HHmmss maybe duplicate the name +++++++++++++++++++++++++++*/
        StringBuffer buf = new StringBuffer(formatDate);
        Random random = new Random();
        for (int i = 0; i < 3; ++i) {
            buf.append(random.nextInt(10));
        }
        return buf.toString();
    }

    public static String unicode2String(String unicode) {
        StringBuffer string = new StringBuffer();
        String[] hex = unicode.split("\\\\u");

        for (int i = 1; i < hex.length; ++i) {
            int data = Integer.parseInt(hex[i], 16);
            string.append((char) data);
        }

        return string.toString();
    }

    /**
     * 根据内容类型判断文件扩展名
     *
     * @param contentType 内容类型
     * @return
     */
    public static String getFileExt(String contentType) {
        String fileExt = "";
        if ("image/jpeg".equals(contentType))
            fileExt = ".jpg";
        else if ("audio/mpeg".equals(contentType))
            fileExt = ".mp3";
        else if ("audio/amr".equals(contentType))
            fileExt = ".amr";
        else if ("video/mp4".equals(contentType))
            fileExt = ".mp4";
        else if ("video/mpeg4".equals(contentType))
            fileExt = ".mp4";
        return fileExt;
    }


    public static String getTimeStamp() {
        StringBuffer buf = new StringBuffer();
        long time = System.currentTimeMillis();
        Random random = new Random();
        buf.append(time);

        for (int i = 0; i < 2; ++i) {
            buf.append(random.nextInt(10));
        }

        return buf.toString();
    }


    public static String filterEmoji(String source) {
        if (source != null) {
            Pattern emoji = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]", Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);
            Matcher emojiMatcher = emoji.matcher(source);
            if (emojiMatcher.find()) {
                source = emojiMatcher.replaceAll("*");
            }
        }
        return source;
    }

}

